package io.github.wanggit.antcms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.wanggit.antcms.server.domain.AntArticle;
import io.github.wanggit.antcms.server.domain.AntArticleCatalog;
import io.github.wanggit.antcms.server.domain.AntCatalog;
import io.github.wanggit.antcms.server.mapper.AntCatalogMapper;
import io.github.wanggit.antcms.server.service.ArticleCatalogService;
import io.github.wanggit.antcms.server.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CatalogServiceImpl extends ServiceImpl<AntCatalogMapper, AntCatalog>
        implements CatalogService {

    @Autowired private ArticleCatalogService articleCatalogService;

    @Override
    public void saveOrUpdateCatalog(AntCatalog catalog) {
        if (null != catalog.getParentId() && catalog.getParentId() <= 0) {
            catalog.setParentId(null);
        }
        AntCatalog entity = null;
        if (null != catalog.getId() && catalog.getId() > 0) {
            entity = getBaseMapper().selectById(catalog.getId());
        } else {
            entity = new AntCatalog();
        }
        entity.setParentId(catalog.getParentId());
        entity.setAliasName(
                StringUtils.hasText(catalog.getAliasName())
                        ? catalog.getAliasName()
                        : catalog.getName());
        entity.setName(catalog.getName());
        entity.setRemark(catalog.getRemark());
        saveOrUpdate(entity);
    }

    @Override
    public void deleteCatalog(Long id) {
        AntCatalog entity = getBaseMapper().selectById(id);
        QueryWrapper<AntCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", entity.getId());
        List<AntCatalog> children = getBaseMapper().selectList(queryWrapper);
        if (null != children && !children.isEmpty()) {
            children.forEach(it -> it.setParentId(entity.getParentId()));
        }
        getBaseMapper().deleteById(id);
        saveBatch(children);
    }

    @Override
    public List<AntCatalog> findCatalogByArticle(AntArticle article) {
        List<AntArticleCatalog> articleCatalogs =
                articleCatalogService.findRelationsByArticle(article);
        List<Long> catalogIds =
                articleCatalogs.stream()
                        .map(AntArticleCatalog::getCatalogId)
                        .collect(Collectors.toList());
        return catalogIds.isEmpty() ? new ArrayList<>() : listByIds(catalogIds);
    }
}
